from google.appengine.ext import webapp
from google.appengine.api import taskqueue, mail
from google.appengine.ext.webapp import template
from src.util import *

class QueuePage(webapp.RequestHandler):
    def get(self):        
        template_values = {
            'page': { 'title': 'Task Queue' , 'name' : 'queue' },
            'appId' : getApplicationInfo().appId,
            'enqueueNotification': self.request.get('enqueueNotification')
        }
        
        self.response.out.write(template.render(get_absolute_path('templates/queue.htm'), template_values))

    def post(self):
        # Because of the queue setting, the first task (not has "doSending" parameter) causes the Task Queue to execute 
        # the second task after a period, not immediately
        taskqueue.add(url='/queue/sendemail', queue_name='sendemail')
        taskqueue.add(url='/queue/sendemail', queue_name='sendemail' , params={
                                                    'doSending': True,
                                                    'appId': getApplicationInfo().appId,
                                                    'receivers': self.request.get('receivers') ,
                                                    'subject': self.request.get('subject'),
                                                    'message':self.request.get('message')})
        self.redirect('/queue?enqueueNotification=true')


class QueueProcessor(webapp.RequestHandler):
    def post(self):
        if self.request.get('doSending'):
            mail.send_mail(sender='do-not-reply@%s.appspotmail.com' % self.request.get('appId'),
                           subject=self.request.get('subject'), to=self.request.get('receivers'),
                           body=self.request.get('message'))
        self.response.set_status(200)
